import { Login,getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { userInfo } from "os";
import config from "@/utils/config.js"

const getDefaultState = () => {
  return {
    token: getToken(),
	baseUrl: config.register,
	upload: config.baseUrl,
	inviteCode:"",
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_INVITE_CODE:(state,inviteCode)=>{
	  state.inviteCode = inviteCode
  }
};

const actions = {
  // user login
  login({ commit },userInfo) {
    const { phone, password } = userInfo;
    return new Promise((resolve, reject) => {
      Login({ phone: phone.trim(), password: password })
        .then((response) => {
          const data  = response;
          commit("SET_TOKEN", data.token);
		  uni.setStorageSync("message",data.message)
          setToken(data.token);
          resolve(response);
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response) => {
          const data = response;
		  // console.log(1,data);

          if (!data) {
            return reject("登录过期，请重新登录");
          }
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    removeToken(); // must remove  token  first
	uni.removeStorageSync('message')
	uni.removeStorageSync('inviteCode')
    commit("RESET_STATE");
	uni.reLaunch({
		url: '/pages/login/index'
	})
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
